/**
 * data中，form 表示请求携带数据
 * firstload为true 表示立即请求一次
 * methods中，loadHandler 表示请求处理器
 * this.onRefresh(callback)用来刷新。
 * this.onLoadList() 用来表示请求处理
 */
export default {
	data() {
		return {
			LOAD_LIST_KEY: 0,
			list: [],
			form: {
				lastId: 0,
				page: 1,
			},
			loading: false,
			finished: false,
		}
	},
	methods: {
		onRefresh(callback) {
			if (typeof this.beforeRefresh === "function") {
				this.beforeRefresh(this.form);
			}
			this.loading = false;
			this.list = [];
			this.finished = false;
			this.form.page = 1;
			this.form.lastId = 0;
			if (typeof callback === "function") {
				this.onLoadList().then(callback);
			} else {
				this.onLoadList();
			}
		},
		async onLoadList() {
			if (this.loading || this.finished) return;

			if (Array.isArray(this.list) && typeof this.loadHandler === "function") {
				this.loading = true;
				const key = ++this.LOAD_LIST_KEY;
				const res = await this.loadHandler(this.form);
				// 两次请求Key不相同，说明此请求已被覆盖，不向下执行
				if (key !== this.LOAD_LIST_KEY) {
					return;
				}
				if (res.currentPage >= res.lastPage) {
					this.finished = true;
				}
				this.form.lastId = res.lastId;
				this.form.page++;
				this.list = this.list.concat(res.list)
				this.loading = false;

				if (typeof this.afterLoadList === "function") {
					this.afterLoadList(res);
				}
			}
		},
	},
	onShow() {
		if (this.$options.firstload) {
			this.onRefresh();
		}
	},
	onReachBottom() {
		this.onLoadList();
	},
}
